import { getEmployeeBaseInfo, getUserBaseInfo, myLogin } from '@/api/user.js'
import { getToken, setToken, removeToken } from '@/utils/auth.js'
const state = {
  token: getToken(),
  userInfo: {} // 定义存储用户信息的state
}

const mutations = {
  // mutations用来修改state
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken(state) {
    state.token = undefined
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  removeUserInfo(state) {
    state.userInfo = {} // 定义设置和清除用户信息
  }
}

const actions = {
  // actions要修改state,必须通过mutations
  async login(context, loginForm) {
    const token = await myLogin(loginForm)
    context.commit('setToken', token)
  },
  logout(context) {
    context.commit('removeToken') // 退出操作清除token
    context.commit('removeUserInfo') // 在退出的时候也清除用户信息
  },
  async getInfo(context) {
    const m = await getUserBaseInfo()
    const n = await getEmployeeBaseInfo(m.userId)
    context.commit('setUserInfo', { ...n, ...m })
    return { ...n, ...m } // 获取用于信息的action返回数据
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

